const jwt = require('jsonwebtoken');
const { User } = require('../models');

// 身份验证中间件
exports.authenticate = async (req, res, next) => {
  try {
    let token;

    // 从Authorization头获取Token
    if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
      token = req.headers.authorization.split(' ')[1];
    }

    if (!token) {
      return res.status(401).json({
        success: false,
        message: '访问被拒绝,请先登录'
      });
    }

    // 验证Token
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    
    // 获取用户信息（排除密码）
    const user = await User.findByPk(decoded.userId);
    if (!user || !user.isActive) {
      return res.status(401).json({
        success: false,
        message: '用户不存在或已被禁用'
      });
    }

    // 将用户信息添加到请求对象
    req.user = user;
    next();
  } catch (error) {
    if (error.name === 'JsonWebTokenError') {
      return res.status(401).json({
        success: false,
        message: '无效的 token'
      });
    }
    if (error.name === 'TokenExpiredError') {
      return res.status(401).json({
        success: false,
        message: 'Token 已过期,请重新登录'
      });
    }
    return res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
};

// 权限验证中间件
exports.authorize = (...roles) => {
  return (req, res, next) => {
    if (!req.user) {
      return res.status(401).json({
        success: false,
        message: '请先登录'
      });
    }

    if (!roles.includes(req.user.role)) {
      return res.status(403).json({
        success: false,
        message: '权限不足,无法访问'
      });
    }

    next();
  };
};

// 可选认证中间件(用于某些接口可以选择性登录)
exports.optionalAuth = async (req, res, next) => {
  try {
    let token;

    if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
      token = req.headers.authorization.split(' ')[1];
      
      try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        const user = await User.findByPk(decoded.userId);
        
        if (user && user.isActive) {
          req.user = user;
        }
      } catch (error) {
        // Token无效时不抛出错误,继续执行
        console.log('可选认证Token无效:', error.message);
      }
    }

    next();
  } catch (error) {
    next(error);
  }
};